#include "jeremy.h"

/* Nastavi budik pro cteni http hlavicek, po vyprseni se ukonci */
int set_http_read_headers_timeout(struct main_structure * jeremy, struct settings * nastaveni)
{
        struct settings * http_timeout;

        /* Nacteni potrebneho casoveho limitu */
        http_timeout = get_settings(nastaveni, HTTP_READ_HEADERS_TIMEOUT);
        if (http_timeout == NULL) return false;

	/* Nastaveni alarmu */
	alarm(atoi(http_timeout->value));

	return true;
}

/* Nacte bajt po bajtu od klienta, v pripade chyby vraci false, jinak true a do pole line ulozi nactenou radku vcetne '\n' */
int read_line_from_client(struct main_structure * jeremy, char line[])
{
	int b;
	int i;
	char buf;

	i = 0;
	while((b = read_byte_from_client(jeremy, &buf)) != false) {
		line[i] = buf;
		i++;
	}
	line[i] = '\0';

	if (i == 0) return false;
	return true;
}

/* Nacte bajt od klienta, v pripade chyby vraci false, jinak true a do *byte ulozi nacteny znak  */
int read_byte_from_client(struct main_structure * jeremy, char * byte) 
{
	int n;

	n = read(jeremy->client_fd, byte, sizeof(char));
	if (n == 1) return true;
	else return false;
}


/* Cekani, az se pripoji klient */
int wait_for_client(struct main_structure * jeremy)
{
	socklen_t client_len; 
	struct sockaddr_in client_address;
	unsigned char * client_ip;

	listen(jeremy->server_fd, 5);
	client_len = sizeof(client_address); 

	jeremy->client_fd = accept(jeremy->server_fd, (struct sockaddr*)&client_address, &client_len); 
	client_ip = (unsigned char *)&client_address.sin_addr.s_addr;
	sprintf(jeremy->client_addr, "%d.%d.%d.%d", *(client_ip), *(client_ip+1), *(client_ip+2), *(client_ip+3));

	return true;
}

/* Zacit naslouchat na zvolenem http portu */
int start_server(struct main_structure * jeremy)
{
	int server_len; 
	struct sockaddr_in server_address; 

	jeremy->server_fd = socket(AF_INET, SOCK_STREAM, 0); 

	server_address.sin_family = AF_INET;
	server_address.sin_addr.s_addr = htonl(INADDR_ANY); 
	server_address.sin_port = htons(jeremy->http_port);
	server_len = sizeof(server_address);
	bind(jeremy->server_fd, (struct sockaddr*)&server_address, server_len);

	return true;
}
